package com.ztao.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.apArticle.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.es.SearchArticleVo;
import com.ztao.mapper.ApArticleMapper;
import com.ztao.service.ApArticleService;
import lombok.SneakyThrows;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ApArticleServiceImpl implements ApArticleService {
    @Resource
    private ApArticleMapper articleMapper;
    @Resource
    private RestHighLevelClient client;
    @SneakyThrows
    @Override
    public ResponseResult esinit() {
        List<ApArticle> apArticlesList = this.articleMapper.selectList(null);
        BulkRequest bulkRequest=new BulkRequest("app_info_article");
        for (ApArticle apArticle : apArticlesList) {
            SearchArticleVo searchArticleVo=new SearchArticleVo();
            BeanUtils.copyProperties(apArticle,searchArticleVo);
            IndexRequest indexRequest=new IndexRequest()
                    .id(searchArticleVo.getId()+"")
                    .source(JSON.toJSONString(searchArticleVo), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return ResponseResult.okResult("导入成功"+apArticlesList.size());
    }


}
